<template>
	<div class="rules_options">
		<el-popover placement="bottom-start" trigger="hover" class="rules_options_wrapper" popper-class="rules_options_popper">
			<!-- <el-button slot="reference">hover 激活</el-button> -->
			<div class="tags" slot="reference">规则选项（{{ data.length }}）</div>
			<template v-if="data.length > 0">
				<el-tag size="small" v-for="(item, index) in data" :key="index" closable disable-transitions @close="handleCloseTag(data, index)">
					{{ item.name }}
				</el-tag>
			</template>
			<template v-else><p class="none">暂无数据</p></template>
		</el-popover>
		<el-input size="small" placeholder="请输入选项" v-model="inputValue" v-if="inputVisible">
			<el-button-group slot="append">
				<el-button type="text" @click="handleConfirmInput()">确定</el-button>
				<el-button type="text" @click="handleCancelInput()">取消</el-button>
			</el-button-group>
		</el-input>
		<el-button v-else class="add_btn" size="medium" @click="handleAddOption()">添加选项</el-button>
	</div>
</template>

<script>
export default {
	props: {
		data: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			inputValue: '',
			inputError: false,
			inputVisible: false
		};
	},
	watch: {
		data: {
			handler(data) {
				// console.log(data);
			},
			immediate: true
		}
	},
	methods: {
		//添加选项
		handleAddOption() {
			this.inputValue = '';
			this.inputVisible = true;
		},

		//确认添加选项
		handleConfirmInput() {
			this.inputError = false;
			if (!this.inputValue) {
				this.inputError = true;
				return false;
			} else if (this.data.some((item) => item.name === this.inputValue)) {
				this.inputError = true;
				return false;
			}
			this.inputVisible = false;
			this.data.push({
				id: this.$genUUID(),
				name: this.inputValue
			});
		},

		//取消添加选项
		handleCancelInput() {
			this.inputValue = '';
			this.inputVisible = false;
		},

		//删除选项
		handleCloseTag(data, index) {
			data.splice(index, 1);
		}
	}
};
</script>

<style lang="scss" scoped>
.rules_options::v-deep {
	.el-input {
		width: 240px;
	}
	.el-button.add_btn {
		padding: 8px;
	}
	.el-input-group__append {
		padding: 0 25px;
	}
	.el-button-group {
		display: flex;
		.el-button {
			padding: 5px;
		}
	}
}
.rules_options_wrapper {
	float: left;
	margin-right: 10px;
	.tags {
		padding: 8px;
		font-size: 14px;
		line-height: 1;
		border: solid 1px #dcdfe6;
	}
}
.option_list {
	padding: 10px;
}
</style>
<style lang="scss">
.rules_options_popper {
	max-width: 480px;
	padding: 10px 0 0 10px;
	.el-tag {
		margin: 0 10px 10px 0;
	}
	p.none {
		text-align: center;
		margin: 0 10px 10px 0;
	}
}
</style>
